<template>
  <div>
    <customDialog
      :title="`${title}`"
      :dialogVisible="dialogVisible"
      @close="cancelDialog"
      :showFoot="false"
      width="800"
    >
      <div class="table_box_wrapper">
        <div class="batch_box" v-if="isMultiple">
          <el-button
            type="primary"
            size="small"
            @click.stop="handleBatch"
            :disabled="!selectionData.length"
          >
            {{ batchBtnText }}
          </el-button>
          <el-alert
            v-if="props.btnText == '取消授权'"
            title="当分销商下的小程序包含有主小程序，取消授权不会取消主小程序的剧目权限"
            type="warning"
            :closable="false"
          />
        </div>
        <custom-table
          :loading="loading"
          :columns="columns"
          :tableData="tableData"
          :pageObj="pageObj"
          @sizechange="sizechange"
          @currentChange="currentChange"
          :isPagination="props.typePower == 2 ? false : true"
          :typeSelect="isMultiple"
          @selectionChange="selectionChange"
          :maxHeight="550"
          class="table_box"
        >
          <!-- @sizechange="sizechange"
          @currentChange="currentChange" -->
          <template #enabled="{ scope }">
            <el-tag v-if="scope.row?.enabled" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
          <template #operator="{ scope }">
            <el-button
              type="primary"
              size="small"
              @click.stop="handleAllocation(scope.row)"
            >
              {{ btnText }}
            </el-button>
          </template>
        </custom-table>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customTable from "@/components/CustomTable/index.vue";
import customDialog from "@/components/CustomDialog/index.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import { getAgentList } from "@/api/auth/index";
import { bindApp } from "@/api/operateCenter/distributor/index";
import {
  agentDistributor,
  deleteAgentDistributor,
  getAgentOperas,
} from "@/api/operateCenter/episode/index";
import { searchTenant } from "@/api/operateCenter/distributor/index";
import { aysnOperas } from "@/api/operateCenter/distributorEpisode/index";
import type { Action } from "element-plus";
import { ElTag } from "element-plus";
import { cloneDeep } from "lodash-es";

const props = defineProps({
  // typePower 类型  1：小程序管理分配  2：剧目管理分销商授权 / 取消授权  3：分销商剧目管理同步剧目
  typePower: {
    type: Number,
    default: 1,
  },
  btnText: {
    type: String,
    default: "分 配",
  },
  title: {
    type: String,
    default: "分配分销商",
  },
  batchBtnText: {
    type: String,
    default: "批量授权",
  },
  isMultiple: {
    type: Boolean,
    default: false,
  },
});

const dialogVisible = ref(false);
const loading = ref<boolean>(false);
const selectionData = ref<Array<any>>([]);
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const form = {
  pageNo: 1,
  pageSize: 10,
  hasMiniApp: true,
};
const formData = ref(Object.assign({}, form));
const tableData = ref<Array<any>>([]);
const powerTableData = ref<Array<any>>([]);

const subData = reactive({
  tenantId: undefined,
  appId: undefined,
});

const tempData = ref<any>();

const columns = reactive([
  { prop: "name", label: "企业名称", minWidth: 120 },
  { prop: "userName", label: "分销商账号", minWidth: 120 },
  { prop: "realName", label: "姓名", minWidth: 110 },
  { prop: "phone", label: "手机号", width: 115 },
  { prop: "enabled", slotName: "enabled", label: "是否启用", width: 80 },
  { prop: "operator", slotName: "operator", label: "操作", width: 120 },
]);

const handleBatch = () => {
  handleAllocation(selectionData.value);
};

// 分配
const emit = defineEmits(["success"]);
const handleAllocation = (val: any) => {
  let URL: any, params: any;
  if (props.typePower == 1) {
    URL = bindApp;
    params = {
      tenantId: val?.id,
      appId: subData.appId,
    };
  } else if (props.typePower == 2) {
    if (!val) return;
    // 如果为多选数组 则取 selectionData的值  否则取操作后面的单个数据 id
    let ids = Array.isArray(val)
      ? selectionData.value.map((x: Record<string, any>) => {
          return x.id.toString();
        })
      : [val.id.toString()];
    if (props.btnText == "取消授权") {
      URL = deleteAgentDistributor;
      params = {
        operaId: tempData.value?.id,
        agentIds: ids,
      };
    } else {
      URL = agentDistributor;
      // 判断剧目ID 是否为数组 ， 数组则是批量授权  否则为单个授权
      let operaIds = Array.isArray(tempData.value)
        ? tempData.value.map((x: Record<string, any>) => {
            return x.id;
          })
        : [tempData.value?.id];
      params = {
        operaIds: operaIds,
        agentIds: ids,
      };
    }
  } else if (props.typePower == 3) {
    let ids = Array.isArray(val)
      ? selectionData.value.map((x: Record<string, any>) => {
          return x.id.toString();
        })
      : [val.id.toString()];
    URL = aysnOperas;
    params = {
      sourceAgentId: tempData.value.sourceAgentId,
      sourceAppId: tempData.value.sourceAppId,
      isExactMatch: false,
      targetAgentIds: ids,
      type: 1,
    };
  }
  if (props.typePower == 3) {
    ElMessageBox.confirm(
      "是否精准同步？精准同步时，则选中需要同步分销商的剧目则完全按照列表选中分销商的剧目覆盖，其余剧目将会被移除！",
      "提醒",
      {
        distinguishCancelAndClose: true,
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }
    )
      .then(() => {
        params.isExactMatch = true;
        params.type = 1;
      })
      .catch((action: Action) => {
        if (action === "cancel") {
          params.isExactMatch = false;
          params.type = 1;
        } else {
          params.type = 2;
        }
      })
      .finally(() => {
        if (params.type === 1) {
          delete params.type;
          URL(params).then(() => {
            ElMessage.success(`${props.btnText}成功`);
            emit("success");
            cancelDialog();
          });
        }
      });
  } else {
    URL(params).then(() => {
      ElMessage.success(`${props.btnText}成功`);
      emit("success");
      cancelDialog();
    });
  }
};

const getList = (val = 0) => {
  if (props.typePower == 2) {
    formData.value.pageSize = 999;
  } else {
    // if (!val) {
    //   formData.value.pageNo = pageObj.pageNo;
    //   formData.value.pageSize = pageObj.pageSize;
    // } else {
    //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
    //   formData.value.pageSize = pageObj.pageSize =
    //     val === 1 ? 10 : pageObj.pageSize;
    // }
    formData.value.pageNo = pageObj.pageNo;
    formData.value.pageSize = pageObj.pageSize;
  }
  loading.value = true;
  searchTenant(formData.value)
    .then((res: Record<string, any>) => {
      let tempD = cloneDeep(res?.data);
      /*
            powerTableData.value.length 有值时，为分销商授权和 取消授权
            如果授权，tableData.value 列表绑定值为没有授权的分销商
            如果为取消授权，tableData.value 列表绑定值已经授权的分销商
        */
      if (powerTableData.value.length && props.btnText == "授权") {
        tableData.value = tempD.filter((m: Record<string, any>) => {
          return !powerTableData.value.some((n: number) => n == m.id);
        });
      } else if (powerTableData.value.length && props.btnText == "取消授权") {
        tableData.value = tempD.filter((m: Record<string, any>) => {
          return powerTableData.value.some((n: number) => n == m.id);
        });
      } else {
        tableData.value = res?.data;
      }
      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

const cancelDialog = () => {
  selectionData.value = [];
  tempData.value = null;
  dialogVisible.value = false;
};

// 多选
const selectionChange = (val: any) => {
  selectionData.value = val;
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

// 获取指定剧目已授权的分销商
const getPowerOperas = (id: number) => {
  getAgentOperas(id).then((res: Record<string, any>) => {
    powerTableData.value = res?.data;
  });
};

// 父级电子显示dialog
const showDialog = (val: Record<string, any>, str: string) => {
  console.log("---显示分配分销商----**----", val, props.typePower);
  // typePower 类型  1：小程序管理分配  2：剧目管理分销商授权 / 取消授权  3：分销商剧目管理同步剧目
  if (props.typePower === 1) {
    subData.appId = val?.id;
  } else if (props.typePower === 2) {
    tempData.value = val;
    // 如果为数组，则是批量授权
    if (!Array.isArray(tempData.value)) {
      getPowerOperas(val.id);
    }
  } else if (props.typePower === 3) {
    tempData.value = val;
  }
  // console.log("tempData.value---", tempData.value);

  dialogVisible.value = true;
  getList();
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.table_box_wrapper {
  margin-top: -15px;

  :deep(.table_content) {
    padding: 10px 0;
  }

  .batch_box {
    display: flex;
    justify-content: flex-start;

    :deep(.el-alert) {
      padding: 2px 6px;
      margin-left: 4px;
      font-size: 12px;
    }
  }
}
</style>
